package com.xhj.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhj.entity.ExcelSubjectData;
import com.xhj.entity.Subject;
import com.xhj.service.SubjectService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //一行一行去读取excel内容
    @Override
    public void invoke(ExcelSubjectData user, AnalysisContext analysisContext) {
        if (user == null) throw new RuntimeException("读取Excel失败！");
        // 添加一级科目
        Subject existOneSubject = existOneSubject(subjectService, user.getOneSubjectName());
        // 未存在该科目
        if (existOneSubject == null){
            existOneSubject = new Subject();
            existOneSubject.setTitle(user.getOneSubjectName());
            existOneSubject.setParentId("0");
            subjectService.save(existOneSubject);
        }
        // 获得一级科目的Id
        String pid = existOneSubject.getId();
        // 查找该一级科目下的二级科目
        Subject existTwoSubject = existTwoSubject(subjectService, user.getTwoSubjectName(), pid);
        if (existTwoSubject == null){
            existTwoSubject = new Subject();
            existTwoSubject.setTitle(user.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            subjectService.save(existTwoSubject);
        }
    }

    //读取excel表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("表头信息");
        System.out.println("表头信息："+headMap);
    }

    //读取完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    private Subject existOneSubject(SubjectService subjectService,String title){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("title",title)
                .eq("parent_id","0");
        return subjectService.getOne(queryWrapper);
    }

    private Subject existTwoSubject(SubjectService subjectService, String twoSubjectName, String pid) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("title",twoSubjectName)
                .eq("parent_id",pid);
        return subjectService.getOne(queryWrapper);
    }
}
